package com.galaxy.controller;

import com.alibaba.fastjson.JSON;
import com.galaxy.util.M;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.GetObjectTagsArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import io.minio.messages.Tags;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;


/**
 * 通用文件获取接口
 * @author anjie
 * @email anjie@032t.com
 * @date 2020年8月10日
 */
@Controller
@RequestMapping("/galaxy")
public class FileGetController {

    @Autowired
    MinioClient minioClient;

//    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 从minio 获取文件 并返回
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws InsufficientDataException
     * @throws NoSuchAlgorithmException
     * @throws InternalException
     * @throws XmlParserException
     * @throws InvalidBucketNameException
     */
    @RequestMapping("/obj/{bn}/**")
    @ResponseBody
    public void get(@PathVariable("bn") String bn,HttpServletRequest request, HttpServletResponse response) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, InvalidBucketNameException, ErrorResponseException {

        this.bucketName = bn;
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!b){
            response.getWriter().println("error No BucketName found");
            return;
        }

        String servletPath = request.getServletPath();
        int index = servletPath.indexOf(bn);
        String path = null;
        if(index!=-1)
            path = servletPath.substring(index + bn.length());

        if(path!=null) {
            InputStream object;
            BufferedInputStream buffin;
            Map<String, String> obj;
            try {
                object = minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(bucketName)
                                .object(path)
                                .build()

                );
                //获取文件对应的 tags
                Tags objectTags = minioClient.getObjectTags(
                        GetObjectTagsArgs.builder()
                                .bucket(bucketName)
                                .object(path)
                                .build()
                );
                obj = objectTags.get();

                buffin = new BufferedInputStream(object);

            } catch (ErrorResponseException e) {
                response.addHeader(HttpHeaders.CONTENT_TYPE,"application/json");
                M err = M.err();
                err.setMsg("参数不正确!");
                String s = JSON.toJSONString(err);
                response.getWriter().println(s);
                return;
            }catch (IllegalArgumentException e){
                response.addHeader(HttpHeaders.CONTENT_TYPE,"application/json");
                M err = M.err();
                err.setMsg("对象名不能为空!");
                String s = JSON.toJSONString(err);
                response.getWriter().println(s);
                return;
            }
            //设置响应头
            response.addHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
            response.addHeader(HttpHeaders.CONTENT_LENGTH,obj.get("size"));
            response.addHeader(HttpHeaders.CONTENT_TYPE,obj.get("contentType"));

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] cache = new byte[4096];
            int nRead = 0;
            while ((nRead = buffin.read(cache)) != -1) {
                bufferedOutputStream.write(cache, 0, nRead);
            }
            bufferedOutputStream.flush();

        }else{
            response.addHeader(HttpHeaders.CONTENT_TYPE,"application/json");
            M err = M.err();
            String s = JSON.toJSONString(err);
            response.getWriter().println(s);
        }

    }

}
